<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/21 0021
 * Time: 11:12
 */
/**
 * @param $configs
 * @return mixed
 * 平滑加权算法
 */
function getRandomUrl($configs) {
    $wConfigs = array();
    foreach ($configs as $idx => $cfg) {
        $weight = isset($cfg['weight']) ? intval($cfg['weight']) : 0;
        if ($weight > 0) {
            for ($i=0; $i<$weight; $i++) {
                $wConfigs[] = $cfg['url'];
            }
        }
    }
    // get a random integer as the index of wConfigs
    $idx = mt_rand(0, count($wConfigs) - 1);
    return $wConfigs[$idx];
}
/**
 * @param $configs
 * 测试
 */
function test()
{
    $configs = array(
        array('url'=>'www.domain1.com', 'weight'=>2),
        array('url'=>'www.domain2.com', 'weight'=>4),
        array('url'=>'www.domain3.com', 'weight'=>1),
        array('url'=>'www.domain4.com', 'weight'=>3),
    );

    // run and get stat result
    echo 'Start running, please wait for a while...', PHP_EOL;
    $num = 10000;
    $stat = array();
    $timeUse = 0;
    for ($i=0; $i<$num; $i++) {
        $startTime = microtime(true);
        $url =getRandomUrl($configs);
        $endTime = microtime(true);
        $timeUse += $endTime - $startTime;
        if (!isset($stat[$url])) {
            $stat[$url] = 0;
        }
        $stat[$url] += 1;
    }
    echo PHP_EOL;
    // output result
    echo str_repeat('-*-*', 10), PHP_EOL;
    echo 'Stat Result:', PHP_EOL;
    foreach ($stat as $url => $times) {
        echo $url,"\t",$times,"\t",round(($times / $num * 100), 2),'%',PHP_EOL;
    }
    echo 'Average Time Cost: ', ($timeUse / $num),'s', PHP_EOL;
    echo PHP_EOL;
}

test();